package com.dk.academic.controller;

import com.dk.academic.common.Common;
import com.dk.academic.controller.base.SuperController;
import com.sun.org.apache.xerces.internal.xs.StringList;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;

/**
 * @Author: 廉雪峰
 * @Date: 2018/10/25 16:22
 * @Version 1.0
 */

@Controller
public class SearchController extends SuperController {

    // 根据索引利用ElasticSearch查询
    // 从切面获取连接，此处省略获取连接代码
    @RequestMapping(value = "/search")
    public String index(@RequestParam(required = false,value = "index") String index,Model model) {
//        GetResponse getResponse = Common.client.prepareGet("mysql_demo", "doc", "1").get();
//        System.out.println("索引库数据：" + getResponse.getSourceAsString());

        // 根据多条件组合与查询
        BoolQueryBuilder qb=QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("title",index )) ;
        // 模糊搜索，凡是带有index的属性均显示
        WildcardQueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery("author", "*"+index);
        SearchRequestBuilder sv=Common.client.prepareSearch("article").setTypes("doc").setQuery(qb).setFrom(0)
                .setSize(100);
        System.out.println(sv.toString());
        SearchResponse response=  sv.get();
        SearchHits searchHits =  response.getHits();
        System.out.println("查询到");
        List<Map<String, String>> hits = new ArrayList<Map<String,String>>();
        for(SearchHit hit:searchHits.getHits()){
            // 测试使用，后使用modle封装dto
            Map<String, String> map = new HashMap<String, String>();
            map.put("journal", String.valueOf(hit.getSource().get("journal")));
            map.put("title", String.valueOf(hit.getSource().get("title")));
            map.put("author", String.valueOf(hit.getSource().get("author")));
            map.put("year", String.valueOf(hit.getSource().get("year")));
            hits.add(map);
            System.out.println(map.get("journal"));
            System.out.println( hit.getSourceAsString());
        }
        // 将搜索的情况反映在前端页面
        model.addAttribute("articles", hits);
        return "theme/search/list";
    }
}
